<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;


use App\Exports\OrderExport;
use App\Models\Order;
use App\Models\UsersWechat;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class OrderController extends Controller
{
    public function __construct()
    {
        $this->middleware('admin');
    }

    public function index(Request $request){
        $param['number'] = safe2($request->input('number',''));
        $param['order_no'] = safe2($request->input('order_no',''));
        $param['type'] = safe2($request->input('type'));
        $param['pay_time'] = $request->input('pay_time');
        $query = Order::with('user')->where('pay_status',2);
        if ($param['number']) {
            $wechat_id = UsersWechat::select('id')->where('number','like',$param['number'])->value('id');
            if ($wechat_id) {
               $query->where('wechat_id',$wechat_id);
            }
        }
        if ($param['order_no']) {
            $query->where('order_no',$param['order_no']);
        }

        if ($param['type']) {
            $query->where('type',$param['type']);
        }

        if ($param['pay_time']) {
            $query->whereDate('pay_time',$param['pay_time']);
        }

        $rows   = $query->orderBy('id','DESC')->paginate(20);
        $data = [
            'rows'=>$rows,
            'param'=>$param,
            'pay_time'=>$param['pay_time'],
        ];
        return view('admin/order/order_list', $data);
    }

    public function export(Request $request){
        $username = safe2($request->input('username'));
        $order_no = safe2($request->input('order_no'));
        $created_at = $request->input('created_at');
        return Excel::download(new OrderExport(compact('username','order_no','created_at')), date("YmdHis").'订单明细.xlsx');
    }

}
